package com.titaniume.java2;

import com.titaniume.java.Employee;
import jdk.nashorn.internal.runtime.regexp.joni.constants.OPCode;
import org.junit.Test;

import java.util.Optional;
import com.titaniume.java.Employee.Status;

/**
 *@program: java8
 *@description:
 *@author: renfei.huang
 *@create: 2021-11-01 10:57
 */
public class TestOptional {

    /*
     * 一、Optional 容器类：用于尽量避免空指针异常
     * 	Optional.of(T t) : 创建一个 Optional 实例
     * 	Optional.empty() : 创建一个空的 Optional 实例
     * 	Optional.ofNullable(T t):若 t 不为 null,创建 Optional 实例,否则创建空实例
     * 	isPresent() : 判断是否包含值
     * 	orElse(T t) :  如果调用对象包含值，返回该值，否则返回t
     * 	orElseGet(Supplier s) :如果调用对象包含值，返回该值，否则返回 s 获取的值
     * 	map(Function f): 如果有值对其处理，并返回处理后的Optional，否则返回 Optional.empty()
     * 	flatMap(Function mapper):与 map 类似，要求返回值必须是Optional
     */


    @Test
    public void test4() {

        Optional<Employee> optional = Optional.ofNullable(new Employee(1000, "张三", 25, 800, Status.FREE));
        Optional<String> str = optional.map((e) -> e.getName());
        System.out.println(str.get());

        Optional<String> optional1 = optional.flatMap((e) -> Optional.of(e.getName()));
        System.out.println(optional1);
    }


    @Test
    public void test3() {
        Optional<Employee> op = Optional.ofNullable(null);
        if (op.isPresent()) {
            System.out.println(op.get());
        }

        Employee employee = op.orElse(new Employee(1000, "张三", 25, 800, Status.FREE));
        System.out.println(employee);

        Employee emp = op.orElseGet(() -> new Employee());
        System.out.println(emp);

    }


    @Test
    public void test2() {
        Optional<Employee> op = Optional.empty();
        System.out.println(op.get());
    }


    @Test
    public void test1() {
        Optional<Employee> op = Optional.of(null);
        Employee employee = op.get();
        System.out.println(employee);
    }


    @Test
    public void test5() {

//        Man man = new Man();
//        String godnessName = getGodnessName(man);
//        System.out.println(godnessName);


        Optional<Godness> gn = Optional.ofNullable(new Godness("剥夺老师"));
        Optional<NewMan> op =Optional.ofNullable(new NewMan(gn));
        String godnessName2 = getGodnessName2(op);
        System.out.println(godnessName2);
    }

    //需求： 获取男人心中女人的名字
    public String getGodnessName(Man man) {
        if (man != null) {
            Godness gn = man.getGod();
            if (gn != null) {
                return gn.getName();
            }
        }
        return "苍老师";
    }

    public String getGodnessName2(Optional<NewMan> man) {

        return man.orElse(new NewMan())
                .getGodness()
                .orElse(new Godness("苍老师"))
                .getName();

    }

}